package simbot.example.service.produce.info.animation;

import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import simbot.example.dto.BangumiDTO;
import simbot.example.entity.BangumiEntity;
import simbot.example.utils.client.HttpClientUtil;

import java.lang.reflect.InvocationTargetException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

/**
 * Bangumi API 服务
 *
 * @author minmin
 * @since 2021 /07/02 22:42
 */
@Service
@Slf4j
public class BangumiService {
    private static final String API_URL = "https://api.bgm.tv/calendar";

    private final LoadingCache<String, String> requestCache = CacheBuilder.newBuilder().maximumSize(10).expireAfterWrite(25, TimeUnit.HOURS).build(new CacheLoader<String, String>() {
        @Override
        public String load(@NotNull String key) {
            log.debug("BangumiService.getAnimationCalendar...");
            return getAnimationCalendar();
        }
    });

    /**
     * Gets animation calendar by daily.
     *
     * @return the animation calendar by daily
     */
    public BangumiDTO getAnimationCalendarByDaily() {
        return getAnimationCalendarByDaily(LocalDate.now().getDayOfWeek());
    }

    /**
     * Gets animation calendar by daily.
     *
     * @param dayOfWeek the day of week
     * @return the animation calendar by daily
     */
    public BangumiDTO getAnimationCalendarByDaily(DayOfWeek dayOfWeek) {
        try {
            return analyticalData(requestCache.get(API_URL), dayOfWeek);
        } catch (Exception e) {
            log.error("BangumiService.analyticalData 出错");
            throw new RuntimeException(e);
        }
    }

    private String getAnimationCalendar() {
        return HttpClientUtil.sendGet(API_URL);
    }

    private BangumiDTO analyticalData(String jsonStr) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        return analyticalData(jsonStr, LocalDate.now().getDayOfWeek());
    }

    private BangumiDTO analyticalData(String jsonStr, DayOfWeek dayOfWeek) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        BangumiEntity[] bangumiEntity = JSONObject.parseObject(jsonStr, BangumiEntity[].class);
        return new BangumiDTO(bangumiEntity, dayOfWeek);
    }
}
